package top.lingkang.ciyuanwaf.config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.id.NanoId;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Init;
import org.noear.solon.annotation.Inject;
import top.lingkang.ciyuanwaf.WebApp;
import top.lingkang.ciyuanwaf.constants.LogType;
import top.lingkang.ciyuanwaf.dao.SettingDao;
import top.lingkang.ciyuanwaf.dao.UserDao;
import top.lingkang.ciyuanwaf.entity.SettingEntity;
import top.lingkang.ciyuanwaf.entity.UserEntity;
import top.lingkang.ciyuanwaf.service.LogService;
import top.lingkang.ciyuanwaf.utils.CommonUtils;
import top.lingkang.ciyuanwaf.utils.terminal.TerminalUtils;
import top.lingkang.hibernate6.transaction.Transaction;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Properties;

/**
 * @author lingkang
 * created by 2023/10/12
 */
@Slf4j
@Component
public class DataInit {

    @Inject
    private SettingDao settingDao;
    @Inject
    private UserDao userDao;
    @Inject
    private LogService logService;

    @Transaction
    @Init
    public void init() {
        logService.add(LogType.start, System.getProperty("user.dir"));
        List<SettingEntity> all = settingDao.findAll();
        if (!all.isEmpty()) {
            if ("true".equals(all.get(0).getIsInit()))
                TerminalUtils.cdNginxDir(WebApp.thread, all.get(0).getNginxPath());
            return;
        }
        log.info("首次运行，初始化数据...");
        SettingEntity setting = new SettingEntity();
        setting.setId("setting");
        setting.setNginxPath("");
        setting.setIsInit("false");
        settingDao.saveOrUpdate(setting);

        UserEntity user = new UserEntity();
        user.setUsername("admin");
        String password = NanoId.randomNanoId(6);
        user.setPassword(CommonUtils.md5(password));
        user.setNickname("管理员");
        userDao.saveOrUpdate(user);
        File pass = new File(WebApp.dir + "data" + File.separator + "password.txt");
        FileUtil.writeString(password, pass, StandardCharsets.UTF_8);
        log.info("首次初始化，admin 密码为：{}", password);
        log.info("您也可以在此找到密码：{}", pass.getAbsolutePath());
    }
}
